package vip.xiaonuo.modular.file.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import vip.xiaonuo.modular.entitys.ImgUrl;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @Description 通过二进制流返回图片前端显示
 * @Author cy
 * @Date 2022/8/9 11:27
 * @Version 1.0
 */
@RestController
public class ImageController {

    @PostMapping(value = "/file/getImg")
    public void getImg(@RequestBody ImgUrl imgUrl, HttpServletResponse response){
        try {
//            String filename = "测试.jpg";//url.split("")[1];
            File file = new File(imgUrl.getUrl());
            FileInputStream fis = new FileInputStream(file);
            byte[] bytes = IOUtils.toByteArray(fis);
            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename=");
            //文件下载类型--二进制文件
            response.setContentType("application/octet-stream;charset=utf-8");
            IOUtils.write(bytes,response.getOutputStream());
            fis.close();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }




    }
}
